using System;
using System.Web.Mvc;
using Autofac.Integration.Mvc;

namespace Limestone.MVC
{

    [ModelBinderType(typeof(Field))]
    public class AbstractFieldBinder : DefaultModelBinder
    {
        protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
        {
            var fieldTypeName = controllerContext.HttpContext.Request.Form[bindingContext.ModelName + ".Type"];

            var typeValue = bindingContext.ValueProvider.GetValue(bindingContext.ModelName + ".ModelType");


            var type = Type.GetType((string)typeValue.ConvertTo(typeof(string)), true);
            var model = Activator.CreateInstance(type);
            bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, type);
            //return model;
            var field = FieldFactory.CreateField(fieldTypeName);

            bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => field,
                                                                                             field.GetType());
            return field;
        }

    }
}